package com.tiancheng.trade.settlement.util;

import com.jcraft.jsch.*;
import com.tiancheng.trade.settlement.configuration.MidasSftpConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

/**
 * SFTP工具类
 */
@Slf4j
@Component
public class SftpUtil {

    @Resource
    MidasSftpConfig midasSftpConfig;

    /**
     * 获取ChannelSftp
     */
    public ChannelSftp getChannelSftp() {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.addIdentity(midasSftpConfig.getIdentityFile(), "");
            Session sshSession = jsch.getSession(midasSftpConfig.getUserName(), midasSftpConfig.getHost(), midasSftpConfig.getPort());
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            log.error("getConnectIP " + e.getMessage());
        }
        return sftp;
    }

    /**
     * 下载
     */
    public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
        } catch (Exception e) {
            log.error("download " + e.getMessage());
        } finally {
            if (sftp.isConnected()) {
                try {
                    Session Session = sftp.getSession();
                    Session.disconnect();
                } catch (JSchException e) {
                    log.error("download sshSession.disconnect " + e.getMessage());
                }
                sftp.disconnect();
            }

        }
    }

}